import { ShallowRef } from "vue";
import { TabsProps } from "../tabs.props";
import { TabPageContext, UseOnePage, UseTabs } from "./types";

export function useOnePage(
    props: TabsProps,
    tabContentElementRef: ShallowRef<any>,
    useTabsComposition: UseTabs
): UseOnePage {

    const pageSelector = '.farris-tab-page';
    const { tabPages } = useTabsComposition;

    function scrollTo(activePageIndex: number) {
        const pageContainer = tabContentElementRef.value;
        if (pageContainer) {
            const pages = tabContentElementRef.value.querySelectorAll(pageSelector);
            if (pages.length > 0) {
                const activePageElement = pages[activePageIndex];
                const { offsetTop } = activePageElement;
                const scrollTop = (offsetTop - 32) > 0 ? (offsetTop - 32) : 0;
                pageContainer.scrollTop = scrollTop;
            }
        }
    }

    function scrollToByPaggId(pageId: string) {
        const activePageIndex = tabPages.value.findIndex((tabPage: TabPageContext) => tabPage.props.id === pageId);
        if (activePageIndex > -1) {
            scrollTo(activePageIndex);
        }
    }

    return { scrollTo, scrollToByPaggId };
}
